from email.mime import base
from os import PRIO_USER
import yaml
from urllib import parse

from dao.dao import MysqlInfo
from service.blog import Blog


SERVICE_CONFIG_PATH = "./service.yml"
COOKIE_PATH = "./cookie.txt"


class SearchInfo:
    def __init__(self, search_title: str, start_time: str, end_time: str) -> None:
        self.search_title = search_title
        self.start_time = start_time
        self.end_time = end_time

    def __str__(self) -> str:
        info = """
        搜索时间：\t%s
        开始时间：\t%s
        结束时间：\t%s
        """ % (self.search_title, self.start_time, self.end_time)
        return info


def read_mysql_config() -> MysqlInfo:
    with open(SERVICE_CONFIG_PATH, "r", encoding="utf-8") as f:
        content = f.read()
        conf = yaml.load(content, yaml.FullLoader)
        mysql_info =  MysqlInfo(
            conf["mysql"]["user"],
            conf["mysql"]["passwd"],
            conf["mysql"]["host"],
            conf["mysql"]["datebase"],
            conf["mysql"]["port"],
        )
        print(mysql_info)
        return mysql_info


def read_search_config() -> SearchInfo:
    with open(SERVICE_CONFIG_PATH, "r", encoding="utf-8") as f:
        content = f.read()
        conf = yaml.load(content, yaml.FullLoader)
        search_info =  SearchInfo(
            conf["weibo"]["search_title"],
            conf["weibo"]["start_time"],
            conf["weibo"]["end_time"],
        )
        print(search_info)
        return search_info


class HotSearch:
    def __init__(self) -> None:
        self.mysql_info = read_mysql_config()
        self.search_info = read_search_config()
        self.base_url = self.generate_url()
        self.service = Blog(COOKIE_PATH, self.base_url, self.mysql_info)

    def generate_url(self) -> str:
        base_url = "https://s.weibo.com/weibo"
        question = parse.quote("上海疫情")
        base_url += "?q=" + question + "&xsort=hot&suball=1&timescope=custom:" 
        base_url += self.search_info.start_time + ":" + self.search_info.end_time + "&Refer=g"

        return base_url

    def start(self):
        self.service.collect_all_blog_info()
        self.service.close()


if __name__ == "__main__":
    search = HotSearch()
    search.start()

